#!/bin/sh
# - test
# - nvme_trtype
# - use_siw

## blktests is a test framework for the Linux kernel block layer and storage stack.

. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/job.sh
. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/reproduce-log.sh
. $LKP_SRC/lib/tests/common.sh

cd $BENCHMARK_ROOT/blktests || die "fail to cd $BENCHMARK_ROOT/blktests"

# https://github.com/osandov/blktests/pull/64
sed -i 's/set -u//' common/multipath-over-rdma

set_env()
{
	local partition
	case "$test" in
	nbd-group-*|loop-group-*)
		partition=""
		;;
	scsi-group-*)
		partition=${partitions%% *}
		is_virt && partition=$(echo "$partition" | sed 's/[0-9]*$//g')
		;;
	srp-group-*)
		log_cmd systemctl stop multipathd
		;;
	block-004)
		log_eval export TIMEOUT=300
		;;
	*)
		partition=${partitions%% *}
		;;
	esac

	if [ -n "$partition" ]; then
		echo "TEST_DEVS=$partition" > config
		[ "$test" = "nvme-group1" ] && log_cmd mkdir -p /mnt/$test && log_cmd mount $partition /mnt/$test
	fi

	[ "$nvme_trtype" ] && echo "nvme_trtype=$nvme_trtype" >> config
	[ "$use_siw" = "true" ] && echo "use_siw=1" >> config

	# fix the issue: losetup: cannot find an unused loop device
	lsmod | grep -q loop || modprobe loop

	# fix blkzone is not available
	ln -sf $BENCHMARK_ROOT/blktests/util-linux/blkzone /usr/bin/blkzone

	# Use build in nvme
	ln -sf "$BENCHMARK_ROOT/blktests/nvme-cli/usr/local/sbin/nvme" /usr/bin/nvme
}

run_test()
{
	local test_dir="$BENCHMARK_ROOT/blktests/tests"

	local all_tests
	local all_tests_cmd

	if [ "${test%[a-z4]-[0-9][0-9][0-9]}" != "$test" ]; then # single test
		all_tests_cmd="echo ${test%-*}/${test#*-}"
	elif [ "${test#*-}" != "$test" ]; then # group tests
		all_tests_cmd="sed \"s:^:${test%%-*}/:\" $test_dir/$test"
	else
		all_tests="$test"
	fi

	[ -n "$all_tests_cmd" ] && {
		log_echo $all_tests_cmd
		all_tests=$(eval "$all_tests_cmd")
	}

	case "$test" in
	nvme-group-*)
		log_cmd ./check -o /mnt/$test $all_tests
		;;
	*)
		log_cmd ./check $all_tests
		;;
	esac
}

read_env_vars
set_env
run_test

[ -d "$BENCHMARK_ROOT/blktests/results" ] && upload_files -t results $BENCHMARK_ROOT/blktests/results/*
[ -d "/mnt/$test/nodev" ] && upload_files -t results /mnt/$test/nodev/*

exit 0
